package com.xz.main;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileWriter;
import java.net.URI;

/**
 * Created by YLZX-Z0107 on 2014/9/11.
 */
public class Proxy {
    private static final String China_ip_ni = "http://www.xici.net.co/nn/";

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();
        CloseableHttpResponse response;
        for (int i = 1; i < 172; i++) {
            URI uri = new URI(China_ip_ni + i);
            httpGet.setURI(uri);
            response = httpclient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            handleIP(result);
        }
    }

    private static void handleIP(String result) throws Exception{
        Document document = Jsoup.parse(result);
        Elements elements = document.select("table#ip_list>tbody>tr");
        for (Element element : elements) {
            writeIP(element.child(1).text() + "---" + element.child(2).text() + "\r\n");
        }
    }

    private static void writeIP(String ip) throws Exception {
        File file = new File("e:/ip.txt");
        if (!file.exists())
            file.createNewFile();
        FileWriter fw = new FileWriter(file, true);
        fw.write(ip);
        fw.flush();
        fw.close();
    }
}
